﻿using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Profiling;

/// <summary>
/// 单个摄像机的渲染过程
/// </summary>
public partial class CameraRenderer 
{
    partial void DrawGizmos ();
    partial void DrawUnsupportedShaders ();
    partial void PrepareForSceneWindow ();
    partial void PrepareBuffer ();
    
#if UNITY_EDITOR
    // 内置shader
    static ShaderTagId[] legacyShaderTagIds = {
        new ShaderTagId("Always"),
        new ShaderTagId("ForwardBase"),
        new ShaderTagId("PrepassBase"),
        new ShaderTagId("Vertex"),
        new ShaderTagId("VertexLMRGBM"),
        new ShaderTagId("VertexLM")
    };
    
    static Material errorMaterial;
    
    /// <summary>
    /// 绘制小工具
    /// </summary>
    partial void DrawGizmos () 
    {
        if (Handles.ShouldRenderGizmos()) {
            context.DrawGizmos(camera, GizmoSubset.PreImageEffects);
            context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
        }
    }
    
    /// <summary>
    /// 绘制无效对象
    /// </summary>
    partial void DrawUnsupportedShaders () 
    {
        if (errorMaterial == null) {
            errorMaterial = new Material(Shader.Find("Hidden/InternalErrorShader"));
        }
        var drawingSettings = new DrawingSettings(legacyShaderTagIds[0], new SortingSettings(camera)){
            overrideMaterial = errorMaterial
        };
        for (int i = 1; i < legacyShaderTagIds.Length; i++) {
            drawingSettings.SetShaderPassName(i, legacyShaderTagIds[i]);
        }
        var filteringSettings = FilteringSettings.defaultValue;
        context.DrawRenderers(
            cullingResults, ref drawingSettings, ref filteringSettings
        );
    }
    
    /// <summary>
    /// 在场景视图中显示并编辑UI
    /// </summary>
    partial void PrepareForSceneWindow () 
    {
        if (camera.cameraType == CameraType.SceneView) 
        {
            ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
        }
    }
    
    string SampleName { get; set; }
    partial void PrepareBuffer () 
    {
        Profiler.BeginSample("Editor Only");
        buffer.name = SampleName = camera.name;
        Profiler.EndSample();
    }
#else
	const string SampleName = bufferName;
#endif
}